from datetime import datetime
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from myadmin.models import Member, Shop, Category, Product
from myadmin.models import Orders, OrdersDetail, Payment
from utils.encrypt import md5
from utils.validate_phone_number import validate_phone_number


# Create your views here.
def index(request):
    """ 移动端首页 """
    # 判断当前店铺信息[没有跳转选择
    shop_info = request.session.get('shopinfo', None)
    if shop_info is None:
        return redirect(reverse('mobile_shop'))

    # 获取当前店铺的菜品类别和菜品信息
    clist = Category.objects.filter(shop_id=shop_info['id'], status=1)  # 菜品类别列表
    product_list = dict()
    for vo in clist:
        plist = Product.objects.filter(category_id=vo.id, status=1)  # 每种菜品类别的菜品信息列表
        product_list[vo.id] = plist

    context = {'categorylist': clist, 'productlist': product_list.items(), 'cid': clist[0]}
    return render(request, 'mobile/index.html', context)


def register(request):
    """ 移动端会员注册/登录页面 """
    return render(request, 'mobile/register.html')


def do_register(request):
    """ 执行移动端会员注册/登录 """
    mobile = request.POST.get('mobile', '')
    verifycode = request.POST.get('code', '')
    cd = request.GET.get('cd', '')
    # print(str(verifycode) != str(cd))
    password = request.POST.get('password', '')
    print(password)

    # 判断输入的手机号是否合规
    if not validate_phone_number(mobile):
        context = {'info': '手机号格式错误！'}
        return render(request, 'mobile/register.html', context)

    if str(verifycode) != '1234':
        context = {'info': '验证码错误'}
        return render(request, 'mobile/register.html', context)

    # 根据手机号获取信息【判断手机号是否注册
    try:
        member = Member.objects.get(mobile=mobile)
        if md5(password) != md5(member.password):
            context = {'info': '密码错误'}
            return render(request, 'mobile/register.html', context)
        # 检验状态是否正常
    except Exception as arr:
        print(arr)
        # 没有注册就添加数据
        mb = Member()
        mb.nickname = "顾客"
        mb.avatar = "moren.png"
        if password:
            mb.password = md5(password)
        mb.mobile = mobile
        mb.status = 1
        mb.create_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        mb.update_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        mb.save()
        member = mb
    if member.status == 1:
        # 将这个会员信息转为字典模式 存在session中
        request.session['mobileuser'] = member.toDict()
        return redirect(reverse('mobile_index'))
    else:
        context = {'info': '此账户信息禁用'}
        return render(request, 'mobile/register.html', context)


def shop(request):
    """ 移动端选择店铺 """
    context = {'shoplist': Shop.objects.filter(status=1)}
    return render(request, 'mobile/shop.html', context)


def select_shop(request):
    """ 执行店铺选择 """

    # 选择店铺清空购物车
    request.session['cartlist'] = {}

    # 获取选择店铺的信息，放置到session中
    sid = request.GET.get('sid', None)
    request.session['shopinfo'] = Shop.objects.get(id=sid).toDict()
    print(request.session['shopinfo'])
    return redirect(reverse('mobile_index'))
    # return render(request, 'mobile/index.html')


def add_orders(request):
    """ 移动端下单 """
    # 尝试从session中获取名字为cart_list的购物车信息，没有返回{}
    cart_list = request.session.get('cartlist', {})
    total_money = 0  # 初始化总金额

    for vo in cart_list.values():
        total_money += int(vo['num']) * int(vo['price'])

    request.session['total_money'] = total_money
    return render(request, 'mobile/order.html')


def do_add_orders(request):
    """ 执行订单添加操作 """
    try:
        # print(request.session.get('shopinfo'))
        # 订单信息添加
        od = Orders()
        od.shop_id = request.session['shopinfo']['id']
        od.member_id = request.session['mobileuser']['id']
        od.user_id = 0
        od.money = request.session['total_money']
        od.status = 1  # 1进行中/2无效/3已完成
        od.payment_status = 2  # 1未支付/2已支付/3已退款
        od.create_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        od.update_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        od.save()

        # 支付信息添加
        op = Payment()
        op.order_id = od.id  # 订单id号
        op.member_id = request.session['mobileuser']['id']
        op.type = 2
        op.bank = request.GET.get('bank', 3)  # 1微信/2余额/3现金/4支付宝
        op.money = request.session['total_money']
        op.status = 1  # 1未支付/2已支付/3已退款
        op.create_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        op.update_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        op.save()

        # 订单详情的添加
        cart_list = request.session.get('cartlist', {})  # 获取购物车中的菜品信息
        # 遍历购物车中的菜品信息 添加到订单详情中
        for item in cart_list.values():
            ov = OrdersDetail()
            ov.order_id = od.id  # 订单id
            ov.product_id = item['id']  # 菜品id
            ov.product_name = item['name']  # 菜品名称
            ov.price = item['price']  # 菜品单价
            ov.quantity = item['num']  # 菜品数量
            ov.status = 1  # 状态  1正常/9删除
            ov.save()

        # 成功后清空购物车和总金额
        del request.session['cart_list']
        del request.session['total_money']
        # return HttpResponse("Y")
    except Exception as arr:
        print(arr, 1)
        # return HttpResponse("N")
    return render(request, 'mobile/order_info.html', {'order': od})
